package com.cincc.taofangwang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.taofangwang.R;
import com.cincc.taofangwang.adapter.HistoryAdapter;
import com.cincc.taofangwang.adapter.RecordAdapter;
import com.cincc.taofangwang.common.MyUtils;
import com.cincc.taofangwang.common.OkHttpUtils;
import com.cincc.taofangwang.common.callback.OnClickCallBack;
import com.cincc.taofangwang.constant.CallConstant;
import com.cincc.taofangwang.model.HistoryModel;
import com.cincc.taofangwang.model.RecordModel;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.acl.Group;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class HistoryFragment extends Fragment {
    private static final String TAG = "HistoryFragment";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_history, container, false);
        initView(view);
        return view;
    }

    SmartRefreshLayout refreshLayout;
    HistoryAdapter historyAdapter;

    private void initView(View view) {
        Toolbar toolbar = view.findViewById(R.id.toolbar);
        int statusBarHeight = ImmersionBar.getStatusBarHeight(this);
        AppBarLayout.LayoutParams lp = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
        lp.topMargin = statusBarHeight + 10;
        TextView title = view.findViewById(R.id.title_text);
        title.setText("呼叫历史");

        ImageView quitImg = view.findViewById(R.id.quit_img);
        quitImg.setOnClickListener(v -> quit());

        refreshLayout = view.findViewById(R.id.refreshLayout);
        ListView listView = view.findViewById(R.id.listview);
        View headerView = getLayoutInflater().inflate(R.layout.layout_history_header, null);
        initSearchInfo(headerView);

        refreshLayout.setOnRefreshListener(refreshLayout -> search(true));
        refreshLayout.setOnLoadMoreListener(refreshLayout -> search(false));

        listView.addHeaderView(headerView);

        historyAdapter = new HistoryAdapter(requireActivity(), list);
        listView.setAdapter(historyAdapter);
        historyAdapter.setCallBack(index -> getXPhone(list.get(index)));
    }

    List<HistoryModel> list = new ArrayList<>();

    //每次加载数量
    int limit = 10;
    //加载位置
    int start = 0;

    private void search(boolean isRefresh) {
        try {
            if (isRefresh) {
                start = 0;
                list.clear();
            }
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("start_time_FROM", MyUtils.getTimeStr(beginTime));
            c.put("start_time_TO", MyUtils.getTimeStr(endTime));
            c.put("calling_number", CallConstant.NAME);
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Record");
            jsonObject.put("act", "callHistory");
            jsonObject.put("limit", limit);
            jsonObject.put("start", start);
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            searchRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void refreshUI(JSONArray array) {
        try {
            for (int i = 0; i < array.length(); i++) {
                HistoryModel historyModel = new HistoryModel(
                        array.getJSONObject(i).getString("callNo"),
                        array.getJSONObject(i).getString("startTime"),
                        array.getJSONObject(i).getString("telX"),
                        array.getJSONObject(i).getString("userData")
                );
                list.add(historyModel);
            }
            start = list.size();
            historyAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void searchRequest(String data) {
        Log.e(TAG, "searchRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        if (jsonObject.has("data")) {
                            JSONArray data1 = jsonObject.getJSONArray("data");
                            requireActivity().runOnUiThread(() -> refreshUI(data1));
                        } else {
                            Log.e(TAG, "searchRequest onSuccessful: 没有数据");
                        }
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }

    long beginTime;
    long endTime;
    EditText numberEdit;
    TextView beginText, endText;

    private void initSearchInfo(View view) {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(Calendar.HOUR_OF_DAY, 0);
        startCalendar.set(Calendar.MINUTE, 0);
        startCalendar.set(Calendar.SECOND, 0);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(Calendar.HOUR_OF_DAY, 23);
        endCalendar.set(Calendar.MINUTE, 59);
        endCalendar.set(Calendar.SECOND, 59);

        beginTime = startCalendar.getTimeInMillis();
        endTime = endCalendar.getTimeInMillis();
        beginText = view.findViewById(R.id.begin_time_tv);
        endText = view.findViewById(R.id.end_time_tv);
        numberEdit = view.findViewById(R.id.edit_number);
        RelativeLayout searchLayout = view.findViewById(R.id.search_btn);

        beginText.setText(MyUtils.getCurrentTime(beginTime));
        endText.setText(MyUtils.getCurrentTime(endTime));
        searchLayout.setOnClickListener(v -> search(true));
        beginText.setOnClickListener(v -> showBeginDialog());
        endText.setOnClickListener(v -> showEndDialog());
    }

    private void showBeginDialog() {
        new CardDatePickerDialog.Builder(requireActivity())
                .setTitle("请选择开始时间")
                .setOnChoose("确定", aLong -> {
                    Log.e(TAG, "showBeginDialog: " + aLong);
                    beginTime = aLong;
                    beginText.setText(MyUtils.getCurrentTime(beginTime));
                    return null;
                }).setDefaultTime(beginTime).build().show();
    }

    private void showEndDialog() {
        new CardDatePickerDialog.Builder(requireActivity())
                .setTitle("请选择结束时间")
                .setOnChoose("确定", aLong -> {
                    Log.e(TAG, "showBeginDialog: " + aLong);
                    endTime = aLong;
                    endText.setText(MyUtils.getCurrentTime(endTime));
                    return null;
                }).setDefaultTime(endTime).build().show();
    }


    private void quit() {
        new XPopup.Builder(getContext()).asConfirm("提示", "确定要退出登录吗？",
                        () -> {
                            Intent i = new Intent(requireActivity(), LoginActivity.class);
                            requireActivity().startActivity(i);
                            requireActivity().finish();
                        })
                .show();
    }

    private void getXPhone(HistoryModel item) {
        try {
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("vcc_id", CallConstant.VCCID);
            c.put("calling_number", CallConstant.NAME);
            c.put("called_number", item.userData);
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Task");
            jsonObject.put("act", "setXPhone");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            getXPhoneRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getXPhoneRequest(String data) {
        Log.e(TAG, "getXPhoneRequest: " + data);
        BasePopupView show = new XPopup.Builder(requireActivity()).asLoading().show();
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        String xPhone = data1.getJSONObject(0).getString("xphone");
                        MyUtils.jumpDial(requireActivity(), xPhone);
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    requireActivity().runOnUiThread(show::dismiss);
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                    show.dismiss();
                });
            }
        });
    }
}
